package muilty_thread.java_current_practice_and_kernel.cp5;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

public class Memorizer3<A,V>  implements Computable<A,V> {

    private final Map<A, Future<V>> cache = new ConcurrentHashMap<>();
    private final Computable<A, V> c;

    public Memorizer3(Computable<A, V> c) {
        this.c = c;
    }

    @Override
    public V compute(final A arg) throws InterruptedException {
        Future<V> f = cache.get(arg);
        if (f == null) {
            FutureTask<V> ft = new FutureTask<>(() -> {
                return c.compute(arg);
            });

            f = ft;
            //原子方法
            cache.putIfAbsent(arg, ft);

        }
        try {
           return f.get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        return null;
    }
}